import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../base_notifier.dart';

// Todo 数据模型
class Todo {
  final int id;
  final String title;
  final bool isCompleted;

  const Todo({
    required this.id,
    required this.title,
    required this.isCompleted,
  });

  Todo copyWith({
    int? id,
    String? title,
    bool? isCompleted,
  }) {
    return Todo(
      id: id ?? this.id,
      title: title ?? this.title,
      isCompleted: isCompleted ?? this.isCompleted,
    );
  }

  @override
  String toString() => 'Todo(id: $id, title: $title, isCompleted: $isCompleted)';
}

// TodoList Notifier - 演示列表数据的状态管理
class TodoListNotifier extends BaseNotifier<List<Todo>> {
  @override
  Future<void> loadData({bool isRefresh = false}) async {
    await executeAsync(
      () => _fetchTodos(),
      isRefresh: isRefresh,
    );
  }

  // 模拟获取 Todo 列表
  Future<List<Todo>> _fetchTodos() async {
    await Future.delayed(const Duration(seconds: 1));

    // 随机返回空列表或数据列表
    if (DateTime.now().millisecond % 4 == 0) {
      return []; // 空数据，会自动设置为 empty 状态
    }

    return [
      const Todo(id: 1, title: '完成项目文档', isCompleted: false),
      const Todo(id: 2, title: '代码审查', isCompleted: true),
      const Todo(id: 3, title: '测试新功能', isCompleted: false),
    ];
  }

  // 添加新的 Todo
  Future<void> addTodo(String title) async {
    final currentData = state.data ?? <Todo>[];
    final newTodo = Todo(
      id: DateTime.now().millisecondsSinceEpoch,
      title: title,
      isCompleted: false,
    );

    await executeAsync(
      () async {
        await Future.delayed(const Duration(milliseconds: 500));
        return [...currentData, newTodo];
      },
      keepDataOnError: true,
    );
  }

  // 切换 Todo 完成状态
  Future<void> toggleTodo(int id) async {
    final currentData = state.data ?? <Todo>[];

    await executeAsync(
      () async {
        await Future.delayed(const Duration(milliseconds: 300));
        return currentData.map((todo) {
          if (todo.id == id) {
            return todo.copyWith(isCompleted: !todo.isCompleted);
          }
          return todo;
        }).toList();
      },
      keepDataOnError: true,
    );
  }

  // 删除 Todo
  Future<void> deleteTodo(int id) async {
    final currentData = state.data ?? <Todo>[];

    await executeAsync(
      () async {
        await Future.delayed(const Duration(milliseconds: 300));
        return currentData.where((todo) => todo.id != id).toList();
      },
      keepDataOnError: true,
    );
  }
}

// Provider 定义
final todoListProvider = NotifierProvider<TodoListNotifier, BaseState<List<Todo>>>(() {
  return TodoListNotifier();
});

// 计算属性：未完成的 Todo 数量
final uncompletedTodoCountProvider = Provider<int>((ref) {
  final todoState = ref.watch(todoListProvider);
  if (!todoState.hasData) return 0;

  return todoState.data!.where((todo) => !todo.isCompleted).length;
});

// 计算属性：已完成的 Todo 列表
final completedTodosProvider = Provider<List<Todo>>((ref) {
  final todoState = ref.watch(todoListProvider);
  if (!todoState.hasData) return [];

  return todoState.data!.where((todo) => todo.isCompleted).toList();
});